<template>
  <view class="settlement-container no-scroll bg-gray-100 pb-75">
    <!-- 使用S1Header组件 -->
    <S1Header title="还款收银台" :on-back="handleBack" />

    <!-- 金额信息区域 -->
    <view class="px-3 py-2">
      <!-- 应收区块 - 白色卡片 -->
      <view class="rounded-sm bg-white p-3">
        <!-- 应收金额 -->
        <view class="flex items-center justify-between">
          <text class="text-base text-black">
            欠款总额
          </text>
          <text class="text-lg text-black font-medium">
            {{
              repaymentData.totalDebt
            }}
          </text>
        </view>

        <!-- 优惠/多收选择 - 添加输入框 -->
        <view class="mt-2 flex items-center">
          <view class="flex overflow-hidden rounded-sm">
            <view
              class="cursor-pointer px-3 py-1.5 text-base" :class="[
                repaymentData.discountType === 'discount'
                  ? 'bg-green-500 text-white'
                  : 'bg-gray-200 text-gray-700',
              ]" @click="toggleDiscountType('discount')"
            >
              优惠
            </view>
            <view
              class="cursor-pointer px-3 py-1.5 text-base" :class="[
                repaymentData.discountType === 'more'
                  ? 'bg-green-500 text-white'
                  : 'bg-gray-200 text-gray-700',
              ]" @click="toggleDiscountType('more')"
            >
              多收
            </view>
          </view>
          <view class="flex-1 text-right">
            <input
              v-model="repaymentData.adjustAmountStr" type="text"
              class="inline-block min-w-24 border border-gray-200 rounded-sm px-3 py-1.5 text-right"
              :class="repaymentData.discountType === 'discount' ? 'text-red-500' : 'text-green-500'"
              placeholder="0" readonly @focus="setActiveInput('adjust')"
            >
          </view>
        </view>

        <!-- 实收金额 - 改为输入框 -->
        <view class="mt-2 border border-green-500 rounded-sm bg-green-50 p-3">
          <view class="flex items-center justify-between">
            <text class="text-base text-black">
              现金
            </text>
            <input
              v-model="repaymentData.cashAmountStr" type="text"
              class="border-none bg-transparent text-right text-lg text-green-500 font-medium outline-none"
              placeholder="0" readonly @focus="setActiveInput('cash')"
            >
          </view>
        </view>

        <!-- 备注信息 (移动到这里) -->
        <view class="mt-3">
          <view class="mb-1 text-base text-gray-500">
            还款备注
          </view>
          <textarea
            v-model="repaymentData.notesStr"
            class="h-10 w-full border border-gray-200 rounded-sm p-2 text-sm" placeholder="请输入还款备注信息"
            style="min-height: 40px; max-height: 40px;"
          />
        </view>

        <!-- 支付方式选择 -->
        <view class="grid grid-cols-5 mt-3 gap-1 rounded-sm bg-gray-50 p-2">
          <!-- 现金支付 -->
          <view class="relative" @click="selectPaymentMethod('cash')">
            <view
              v-if="repaymentData.paymentMethod === 'cash'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              1
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                repaymentData.paymentMethod === 'cash' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-cash-multiple mb-1 text-xl" :class="[
                    repaymentData.paymentMethod === 'cash' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    repaymentData.paymentMethod === 'cash' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  现金
                </text>
              </view>
            </view>
          </view>

          <!-- 微信支付 -->
          <view class="relative" @click="selectPaymentMethod('wechat')">
            <view
              v-if="repaymentData.paymentMethod === 'wechat'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              2
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                repaymentData.paymentMethod === 'wechat' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-wechat mb-1 text-xl" :class="[
                    repaymentData.paymentMethod === 'wechat' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    repaymentData.paymentMethod === 'wechat' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  微信
                </text>
              </view>
            </view>
          </view>

          <!-- 支付宝 -->
          <view class="relative" @click="selectPaymentMethod('alipay')">
            <view
              v-if="repaymentData.paymentMethod === 'alipay'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              3
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                repaymentData.paymentMethod === 'alipay' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-alpha-a-circle mb-1 text-xl" :class="[
                    repaymentData.paymentMethod === 'alipay' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    repaymentData.paymentMethod === 'alipay' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  支付宝
                </text>
              </view>
            </view>
          </view>

          <!-- 银联 -->
          <view class="relative" @click="selectPaymentMethod('unionpay')">
            <view
              v-if="repaymentData.paymentMethod === 'unionpay'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              4
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                repaymentData.paymentMethod === 'unionpay' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-credit-card mb-1 text-xl" :class="[
                    repaymentData.paymentMethod === 'unionpay' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    repaymentData.paymentMethod === 'unionpay' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  银联
                </text>
              </view>
            </view>
          </view>

          <!-- 其他 -->
          <view class="relative" @click="selectPaymentMethod('other')">
            <view
              v-if="repaymentData.paymentMethod === 'other'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              5
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                repaymentData.paymentMethod === 'other' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-dots-horizontal mb-1 text-xl" :class="[
                    repaymentData.paymentMethod === 'other' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    repaymentData.paymentMethod === 'other' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  其他
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 软键盘固定在底部 -->
    <view class="fixed bottom-0 left-0 right-0 z-10">
      <!-- 使用数字键盘组件 -->
      <NumberKeyboard
        :actual-amount="totalDebt" :debt-amount="remainingDebt" :show-debt-button="false"
        @key-press="handleKeyPress" @delete="handleDelete" @clear="handleClear" @debt="handleCheckout"
        @checkout="handleCheckout"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import type { HuankuanDataReq } from '@/api/order/types';
import { computed, onMounted, reactive, ref } from 'vue';

import { huankuanData } from '@/api/order';
import * as NumberKeyboard from '@/components/number-keyboard/index.vue';
import S1Header from '@/components/S1Header.vue';

// 定义还款数据接口
interface RepaymentData {
  // 支付金额
  cash_num: number; // 现金支付金额
  wepay_num: number; // 微信支付金额
  alipay_num: number; // 支付宝支付金额
  union_num: number; // 银联支付金额
  other_num: number; // 其他支付金额

  // 金额计算
  totalDebt: number; // 欠款总额
  repayAmount: number; // 实际还款金额

  // 优惠/多收相关
  input_num: number; // 输入的调整金额
  discount_num: string; // 优惠/多收金额(带正负号)
  discountType: string; // 'discount' 为优惠, 'more' 为多收
  value: number; // 优惠为0，多收为1
  adjustAmountStr: string; // 优惠/多收输入框的字符串值

  // 订单相关
  orderIds: number[]; // 已选择的订单ID列表
  maijia_id: number; // 买家ID

  // 备注
  notesStr: string; // 备注字符串

  // UI状态(不提交到API)
  paymentMethod: string; // 当前选择的支付方式
  cashAmountStr: string; // 现金输入框的字符串值
}

// 使用reactive创建还款数据对象
const repaymentData = reactive<RepaymentData>({
  // 支付金额
  cash_num: 0,
  wepay_num: 0,
  alipay_num: 0,
  union_num: 0,
  other_num: 0,

  // 金额计算
  totalDebt: 0,
  repayAmount: 0,

  // 优惠/多收相关
  input_num: 0,
  discount_num: '0',
  discountType: 'discount',
  value: 0,
  adjustAmountStr: '0',

  // 订单相关
  orderIds: [],
  maijia_id: 0,

  // 备注
  notesStr: '',

  // UI状态
  paymentMethod: 'cash',
  cashAmountStr: '0',
});

const activeInput = ref('cash'); // 当前激活的输入框：'adjust' 或 'cash'

// 计算实际应收金额（应收减去优惠或加上多收）
const actualAmount = computed(() => {
  const adjustValue = repaymentData.input_num;
  if (repaymentData.discountType === 'discount') {
    return repaymentData.totalDebt - adjustValue;
  }
  else {
    return repaymentData.totalDebt + adjustValue;
  }
});

// 计算剩余欠款金额
const remainingDebt = computed(() => {
  let payAmount = 0;

  // 根据支付方式获取相应的金额
  switch (repaymentData.paymentMethod) {
    case 'cash':
      payAmount = repaymentData.cash_num;
      break;
    case 'wechat':
      payAmount = repaymentData.wepay_num;
      break;
    case 'alipay':
      payAmount = repaymentData.alipay_num;
      break;
    case 'unionpay':
      payAmount = repaymentData.union_num;
      break;
    case 'other':
      payAmount = repaymentData.other_num;
      break;
  }

  return Math.max(0, actualAmount.value - payAmount);
});

// 总欠款金额
const totalDebt = computed(() => {
  return repaymentData.totalDebt;
});

// 更新当前支付方式的金额
const updatePaymentAmount = (amount: number) => {
  switch (repaymentData.paymentMethod) {
    case 'cash':
      repaymentData.cash_num = amount;
      break;
    case 'wechat':
      repaymentData.wepay_num = amount;
      break;
    case 'alipay':
      repaymentData.alipay_num = amount;
      break;
    case 'unionpay':
      repaymentData.union_num = amount;
      break;
    case 'other':
      repaymentData.other_num = amount;
      break;
  }

  // 更新实际还款金额
  repaymentData.repayAmount = amount;
};

// 同步调整金额到对象
const syncAdjustAmount = () => {
  const inputNum = Number.parseFloat(repaymentData.adjustAmountStr) || 0;
  repaymentData.input_num = inputNum;

  // 设置优惠/多收标识和金额
  repaymentData.value = repaymentData.discountType === 'discount' ? 0 : 1;
  repaymentData.discount_num = repaymentData.discountType === 'discount'
    ? (-inputNum).toString()
    : inputNum.toString();

  // 更新实收金额
  repaymentData.repayAmount = actualAmount.value;
};

// 同步现金金额到对象
const syncCashAmount = () => {
  const amount = Number.parseFloat(repaymentData.cashAmountStr) || 0;
  updatePaymentAmount(amount);
};

// 切换优惠/多收选择
const toggleDiscountType = (type: string) => {
  repaymentData.discountType = type;
  syncAdjustAmount(); // 重新计算相关值
};

// 格式化当前时间
const formatTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 从本地存储加载还款数据
const loadRepaymentData = () => {
  try {
    // 从本地存储获取还款数据
    const storedData = uni.getStorageSync('repaymentData');

    if (storedData) {
      // 设置订单ID列表
      if (storedData.orderIds && Array.isArray(storedData.orderIds)) {
        repaymentData.orderIds = storedData.orderIds;
      }

      // 设置买家ID
      if (storedData.maijia_id) {
        repaymentData.maijia_id = storedData.maijia_id;
      }

      // 设置金额相关信息
      if (storedData.totalDebt !== undefined) {
        repaymentData.totalDebt = Number.parseFloat(storedData.totalDebt) || 0;
        // 默认设置现金金额为欠款总额
        repaymentData.cash_num = repaymentData.totalDebt;
        repaymentData.cashAmountStr = repaymentData.totalDebt.toString();
      }

      // 更新实际还款金额
      repaymentData.repayAmount = repaymentData.cash_num;

      // 读取完后清除本地存储（可选）
      uni.removeStorageSync('repaymentData');
    }
    else {
      console.error('本地存储中未找到还款数据');
      uni.showToast({
        title: '获取还款数据失败',
        icon: 'none',
      });

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack({
          delta: 1,
        });
      }, 1000);
    }
  }
  catch (error) {
    console.error('获取还款数据失败:', error);
    uni.showToast({
      title: '获取还款数据失败',
      icon: 'none',
    });
  }
};

// 在页面加载时获取传递过来的参数
onMounted(() => {
  loadRepaymentData();
});

// 设置当前激活的输入框
const setActiveInput = (inputType: string) => {
  activeInput.value = inputType;
};

// 处理返回按钮点击
const handleBack = () => {
  uni.navigateBack();
};

// 处理数字键盘按键
const handleKeyPress = (key: string) => {
  if (activeInput.value === 'adjust') {
    // 处理优惠/多收输入
    if (repaymentData.adjustAmountStr === '0' && key !== '.') {
      repaymentData.adjustAmountStr = key;
    }
    else {
      // 检查是否已经有小数点
      if (key === '.' && repaymentData.adjustAmountStr.includes('.')) {
        return;
      }
      // 最多两位小数
      if (
        repaymentData.adjustAmountStr.includes('.')
        && repaymentData.adjustAmountStr.split('.')[1].length >= 2
        && key !== '.'
      ) {
        return;
      }
      repaymentData.adjustAmountStr += key;
    }
    syncAdjustAmount();
  }
  else if (activeInput.value === 'cash') {
    // 处理现金输入
    if (repaymentData.cashAmountStr === '0' && key !== '.') {
      repaymentData.cashAmountStr = key;
    }
    else {
      // 检查是否已经有小数点
      if (key === '.' && repaymentData.cashAmountStr.includes('.')) {
        return;
      }
      // 最多两位小数
      if (
        repaymentData.cashAmountStr.includes('.')
        && repaymentData.cashAmountStr.split('.')[1].length >= 2
        && key !== '.'
      ) {
        return;
      }
      repaymentData.cashAmountStr += key;
    }
    syncCashAmount();
  }
};

// 处理删除键
const handleDelete = () => {
  if (activeInput.value === 'adjust') {
    if (repaymentData.adjustAmountStr.length > 1) {
      repaymentData.adjustAmountStr = repaymentData.adjustAmountStr.slice(0, -1);
    }
    else {
      repaymentData.adjustAmountStr = '0';
    }
    syncAdjustAmount();
  }
  else if (activeInput.value === 'cash') {
    if (repaymentData.cashAmountStr.length > 1) {
      repaymentData.cashAmountStr = repaymentData.cashAmountStr.slice(0, -1);
    }
    else {
      repaymentData.cashAmountStr = '0';
    }
    syncCashAmount();
  }
};

// 处理清除键
const handleClear = () => {
  if (activeInput.value === 'adjust') {
    repaymentData.adjustAmountStr = '0';
    syncAdjustAmount();
  }
  else if (activeInput.value === 'cash') {
    repaymentData.cashAmountStr = '0';
    syncCashAmount();
  }
};

// 选择支付方式
const selectPaymentMethod = (method: string) => {
  repaymentData.paymentMethod = method;

  // 如果切换到非现金支付方式，默认设置支付金额等于欠款总额
  if (method !== 'cash') {
    updatePaymentAmount(repaymentData.totalDebt);
    repaymentData.cashAmountStr = repaymentData.totalDebt.toString();
  }
  else {
    // 如果是现金，显示已设置的现金金额
    repaymentData.cashAmountStr = repaymentData.cash_num.toString();
    activeInput.value = 'cash';
  }
};

// 处理收银按钮
const handleCheckout = async (status: number) => {
  // 收银逻辑，这里可以调用API等
  if (repaymentData.repayAmount <= 0) {
    uni.showToast({
      title: '还款金额必须大于0',
      icon: 'none',
    });
    return;
  }

  // 这里可以添加提交还款的逻辑
  uni.showLoading({
    title: '处理中...',
  });

  try {
    // 准备提交的数据
    const orderData: HuankuanDataReq = {
      maijia_id: repaymentData.maijia_id,
      order_id: repaymentData.orderIds,
      cash_num: repaymentData.cash_num,
      wepay_num: repaymentData.wepay_num,
      alipay_num: repaymentData.alipay_num,
      union_num: repaymentData.union_num,
      other_num: repaymentData.other_num,
      notes: repaymentData.notesStr,
      heji: repaymentData.totalDebt.toString(),
      yingshou: actualAmount.value.toString(),
      shishou: repaymentData.repayAmount.toString(),
      discount_num: Number.parseFloat(repaymentData.discount_num),
      input_num: repaymentData.input_num.toString(),
      value: repaymentData.value,
    };
    console.log(huankuanData);

    const res = await huankuanData(orderData);

    if (res.code === 200) {
      uni.showToast({
        title: '还款成功',
        icon: 'success',
        duration: 2000,
      });
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack({
          delta: 1,
        });
      }, 1500);
    }
    else {
      throw new Error(res.msg || '还款失败');
    }
  }
  catch (error) {
    console.error('还款失败:', error);
    uni.showToast({
      title: '还款失败，请重试',
      icon: 'none',
    });
  }
  finally {
    uni.hideLoading();
  }
};
</script>

<style lang="scss">
.settlement-container {
    width: 100%;
    min-height: 100vh;
}

.key-btn {
    user-select: none;
}

input,
textarea {
    outline: none;
}

.no-scroll {
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}
</style>
